<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑文章</title>
    <meta name="description" content="Free Bootstrap 4 Admin Theme | Pike Admin">
    <!--引入adminkit模板-->
    <link href="adminkit/css/app.css" rel="stylesheet">
    <!-- Favicon -->
    <link rel="shortcut icon" href="background/images/favicon.ico">
    <!-- Switchery css -->
    <link href="background/plugins/switchery/switchery.min.css" rel="stylesheet"/>
    <!-- Bootstrap CSS -->
    <link href="background/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <!--  下拉复选框  -->
    <link href="background/css/bootstrap-select.min.css" rel="stylesheet">

    <!-- Font Awesome CSS -->
    <link href="background/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
    <!-- Custom CSS -->
    <link href="background/css/style.css" rel="stylesheet" type="text/css"/>
    <!-- BEGIN CSS for this page -->
    <link rel="stylesheet" type="text/css" href="common/css/dataTables.bootstrap4.min.css"/>
    <link rel="stylesheet" href="background/EditorMD/lib/codemirror/codemirror.min.css">
    <link rel="stylesheet" href="background/EditorMD/css/editormd.css">
    <link rel="stylesheet" href="common/tagsinput/jquery-tagsinput.min.css">
    <style>
        /*.tag {*/
        /*    color: white;*/
        /*}*/
        /*.filter-option-inner-inner{*/
        /*    background-color: white;!important;*/
        /*}*/
        /*.dropdown-toggle {*/
        /*    background-color: white;!important;*/
        /*    border: solid 1px #cccccc;!important;*/
        /*}*/
    </style>
    <!-- END CSS for this page -->
</head>
<body >
<div class="wrapper">
    <nav id="sidebar" class="sidebar">
        <div class="sidebar-content js-simplebar">
            <a class="sidebar-brand" href="#">
                <span class="align-middle">后台管理</span>
            </a>

            <ul class="sidebar-nav">

                <li class="sidebar-item ">
                    <a class="sidebar-link" th:href="@{/dashboard}">
                        <i class="align-middle" data-feather="sliders"></i> <span class="align-middle">首页</span>
                    </a>
                </li>


                <li class="sidebar-item active">
                    <a class="sidebar-link" href="/publishedArticleManage">
                        <i class="align-middle" data-feather="book"></i> <span class="align-middle">文章管理</span>
                    </a>
                </li>

                <li class="sidebar-item">
                    <a class="sidebar-link" href="/kindManage">
                        <i class="align-middle" data-feather="credit-card"></i> <span class="align-middle">分类管理</span>
                    </a>
                </li>

                <li class="sidebar-item">
                    <a class="sidebar-link" href="/tagManage">
                        <i class="align-middle" data-feather="tag"></i> <span class="align-middle">标签管理</span>
                    </a>
                </li>
                <li class="sidebar-item">
                    <a class="sidebar-link" th:href="@{/commentManage}">
                        <i class="align-middle" data-feather="message-square"></i> <span class="align-middle">评论管理</span>
                    </a>
                </li>
                <li class="sidebar-item">
                    <a class="sidebar-link" href="/frontInfo">
                        <i class="align-middle" data-feather="airplay"></i> <span class="align-middle">外观管理</span>
                    </a>
                </li>
                <li class="sidebar-item">
                    <a class="sidebar-link" th:href="@{/statistics}">
                        <i class="align-middle" data-feather="box"></i> <span class="align-middle">统计</span>
                    </a>
                </li>
                <li class="sidebar-item">
                    <a class="sidebar-link" href="/adminInfo">
                        <i class="align-middle" data-feather="user"></i> <span class="align-middle">个人信息管理</span>
                    </a>
                </li>
            </ul>


        </div>
    </nav>

    <div class="main">
        <nav class="navbar navbar-expand navbar-light navbar-bg">
            <a class="sidebar-toggle d-flex">
                <i class="hamburger align-self-center"></i>
            </a>
            <a href="/" class="btn btn-outline-info" disabled>返回前台首页</a>

            <div class="navbar-collapse collapse">
                <ul class="navbar-nav navbar-align">
                    <li class="nav-item dropdown">
                        <a class="nav-icon dropdown-toggle" href="#" id="messagesDropdown" data-toggle="dropdown">
                            <div class="position-relative">
                                <i class="align-middle" data-feather="message-square"></i>
                                <span class="indicator" >[[${session.unReadCount}]]</span>
                            </div>
                        </a>
                        <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right py-0" aria-labelledby="messagesDropdown">
                            <div class="dropdown-menu-header">
                                <div class="position-relative">
                                    [[${session.unReadCount}]]条新评论
                                </div>
                            </div>
                            <div class="list-group">
                                <a th:href="@{/commentManage}" class="list-group-item" th:each="comment:${session.unReadComment}">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col-2">
                                            <i class="text-danger" data-feather="alert-circle"></i>
                                        </div>
                                        <div class="col-10">
                                            <div class="text-dark">[[${comment.name}]]</div>
                                            <div class="text-muted small mt-1">[[${comment.content}]]</div>
                                            <div class="text-muted small mt-1">[[${ #dates.format(comment.time,'yyyy年MM月dd日 ')}]]</div>
                                        </div>
                                    </div>
                                </a>
                            </div>
                            <div class="dropdown-menu-footer">
                                <a th:href="@{/commentManage}" class="text-muted">所有评论</a>
                            </div>
                        </div>
                    </li>

                    <li class="nav-item dropdown">
                        <a class="nav-icon dropdown-toggle d-inline-block d-sm-none" href="#" data-toggle="dropdown">
                            <i class="align-middle" data-feather="settings"></i>
                        </a>

                        <a class="nav-link dropdown-toggle d-none d-sm-inline-block" href="#" data-toggle="dropdown" >
                            <img th:src="${session.admin.img}" class="avatar img-fluid rounded mr-1"  th:alt="${session.admin.name}"/> <span class="text-dark">[[${session.admin.name}]]</span>                        </a>
                        <div class="dropdown-menu dropdown-menu-right">
                            <a class="dropdown-item" href="/logout">Log out</a>
                        </div>
                    </li>
                </ul>
            </div>
        </nav>

        <div class="content-page" style="margin: 0px" >

            <!-- Start content -->
            <div class="content">

                <div class="container-fluid">

                    <div class="row">
                        <div class="col-xl-12">
                            <div >
                                <h1 class="main-title float-left">
                                    <th:block th:if="${article.getStatus()==1}">
                                        <i class="fa fa-pencil bigfonts"></i> 编辑已发布的文章 &ensp;
                                    </th:block>
                                    <th:block th:if="${article.getStatus()==2}">
                                        <i class="fa fa-pencil bigfonts"></i> 编辑回收站的文章 &ensp;
                                    </th:block>
                                    <th:block th:if="${article.getStatus()==0}">
                                        <i class="fa fa-pencil bigfonts"></i> 编辑草稿箱的文章 &ensp;
                                    </th:block>

                                </h1>

                                <ol class="breadcrumb float-right">
                                    <li class="breadcrumb-item">文章</li>
                                    <li class="breadcrumb-item active">写文章</li>
                                </ol>

                            </div>
                        </div>
                    </div>


                    <form id="articleForm" onsubmit="return false">
                        <div class="row">
                           <div class="col-4">
                               <div class="form-group">
                                   <div class="col-sm-4">
                                       <th:block th:if="${null == article}">
                                           <img id="articleCoverImg" th:src="@{/background/images/img-upload.png}"
                                                style="height: 64px;width: 64px;">
                                       </th:block>
                                       <th:block th:unless="${null == article}">
                                           <img id="articleCoverImg" th:src="${article.getImg()}"
                                                style="width:160px ;height: 160px;display:block;">
                                       </th:block>
                                   </div>
                               </div>
                               <br>
                               <div class="form-group">
                                   <div class="col-sm-4">
                                       <button class="btn btn-info" style="margin-bottom: 5px;"
                                               id="uploadArticleCoverImg">
                                           <i class="fa fa-picture-o"></i>&nbsp;上传文章主图
                                       </button>
                                   </div>
                               </div>
                           </div>
                            <div class="col-4"></div>
                            <div class="col-4">
                                <button class="btn btn-success btn-sm" id="publishArticle"><i
                                        class="fa fa-send"></i> 保存修改
                                </button>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-12 col-sm-12 col-md-12">
                                <div class="form-group row" style="padding: 0px 10px">
                                    <input type="hidden" id="articleId" th:value="${article.getId()}">
                                    <input type="text" class="form-control col-sm-12" id="title" name="title",
                                           th:value="${article.getTitle()}" autocomplete="off" placeholder="请输入文章标题">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-12 col-sm-12 col-md-12">
                                <div class="form-group row" style="padding: 0px 10px">
                                <textarea class="form-control col-sm-12" id="introduce" name="introduce" maxlength="200"
                                          th:text="${article.getIntroduce()}" placeholder="摘要"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="row" style="　padding-bottom:20px;" >
                            <div class="col-xs-12 col-sm-12 col-md-12">
                                <div class="row">
                                    <div class="col-6">
                                        <label class="col-form-label"><span style="font-weight: bold">文章标签</span>
                                        </label>
                                        <!--                                        style="background-color: white;!important;"-->
                                        <select   class=" form-control selectpicker " id="tags" multiple="multiple" data-style="btn-info" >
                                            <th:block th:each="tag:${tags}">
                                                <option  th:value="${tag.getId()}" th:text="${tag.getName()}"
                                                         th:selected="${map.get(tag.getId())==1}"
                                                >
                                                </option>
                                            </th:block>
                                        </select>
                                    </div>
                                    <div class="col-6">
                                        <label class="col-form-label"><span style="font-weight: bold">文章分类</span>
                                        </label>
                                        <select class="form-control selectpicker" id="kindId" data-style="btn-info"  >
                                            <option th:each="kind:${kinds}" th:value="${kind.getId()}" th:text="${kind.getName()} "
                                                    th:selected="${article.getKindId()==kind.getId()}">
                                            </option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row" style="padding-top:20px;　padding-bottom:20px;">
                            <div class="col-xs-12 col-sm-12 col-md-12" style="height: 100vh">
                                <div id="editormd">
                                    <textarea id="content" name="content" style="display:none;" th:utext="${article.getContent()}"></textarea>
                                </div>
                            </div>
                        </div>

                    </form>

                </div>
                <!-- END container-fluid -->

            </div>
            <!-- END content -->

        </div>
        <!-- END content-page -->

        <!--    <div th:replace="common/bar::#footer"></div>-->

    </div>

</div>
<!-- END main -->
<!--引入adminkit模板-->
<!--这里会让bootstrap-select失效，不知道怎么解决暂时把jQuery和boostrap注释掉-->
<script src="adminkit/js/app.js"></script>

<script src="background/js/modernizr.min.js"></script>
<!--<script src="background/js/jquery.min.js"></script>-->
<script src="background/js/moment.min.js"></script>

<script src="background/js/popper.min.js"></script>
<!--<script src="background/js/bootstrap.min.js"></script>-->
<script src="background/js/bootstrap-select.min.js"></script>

<script src="background/js/detect.js"></script>
<script src="background/js/fastclick.js"></script>
<script src="background/js/jquery.blockUI.js"></script>
<script src="background/js/jquery.nicescroll.js"></script>
<script src="background/js/jquery.scrollTo.min.js"></script>
<script src="background/plugins/switchery/switchery.min.js"></script>

<!-- App js -->
<script src="background/js/pikeadmin.js"></script>

<!-- BEGIN Java Script for this page -->
<!--引入MarkDown-->
<script type="text/javascript" src="background/EditorMD/editormd.amd.min.js"></script>
<script>
    //解决下拉菜单不显示
    $(function () {
        $('.dropdown-toggle').dropdown();

    })
    var editor;
    var obj=document.getElementById("articleCoverImg");
    var obj2=document.getElementById("articleId");
    var src=obj.getAttribute("src");
    var Id=obj2.getAttribute("value");
    console.log(Id);

    $(function () {
        console.log(src);
        editor = editormd("editormd", {
            placeholder: "此处开始编写文章的内容...",
            path: 'background/EditorMD/lib/',
            saveHTMLToTextarea: true,//注意3：这个配置，方便post提交表单
            /**上传图片相关配置如下*/
            imageUpload: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL: "/admin/image/upload",//注意你后端的上传图片服务地址
            taskList: true,
            tocm: true,         // Using [TOCM]
            tex: true,                   // 开启科学公式TeX语言支持，默认关闭
            flowChart: true,             // 开启流程图支持，默认关闭
            sequenceDiagram: true,
            codeFold: true,
            watch: true,
            toolbarIcons: function () {
                // Or return editormd.toolbarModes[name]; // full, simple, mini
                return ["undo", "redo", "|", "bold", "italic", "quote", "uppercase", "lowercase", "|", "h1", "h2", "h3", "h4", "|", "list-ul", "list-ol", "hr", "|", "link", "image", "code", "code-block", "table", "html-entities", "|", "watch", "preview", "clear", "|", "help"]
            },
        });

        //监听粘贴服务
        document.addEventListener('paste', function (event) {
            var items = (event.clipboardData || window.clipboardData).items;
            var file = null;
            if (items && items.length) {
                // 搜索剪切板items
                for (var i = 0; i < items.length; i++) {
                    if (items[i].type.indexOf('image') !== -1) {
                        file = items[i].getAsFile();
                        break;
                    }
                }
            } else {
                alert("当前浏览器不支持");
                return;
            }
            if (!file) {
                return;
            }
            // 此时file就是我们的剪切板中的图片对象
            // 这里是上传
            var xhr = new XMLHttpRequest();
            // 上传结束
            xhr.onload = function () {

            };
            xhr.onerror = function () {
                alert("网络异常，上传失败!");
            };
            var formData = new FormData();
            formData.append("editormd-image-file", file);
            xhr.open('POST', '/admin/image/upload', true);
            xhr.send(formData);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
                        //5.处理返回的结果
                        var obj = xhr.responseText;
                        var objarr = eval("(" + obj + ")");
                        if (objarr["success"] == 1) {
                            editor.insertValue("![](" + objarr["url"] + ")");
                        } else {
                            alert("粘贴图片失败!");
                        }
                    }
                }
            }
        });

        //图片上传插件初始化 用于预览图上传
        new AjaxUpload('#uploadArticleCoverImg', {
            action: '/admin/image/uploads',
            name: 'image',
            autoSubmit: true,
            responseType: "json",
            onSubmit: function (file, extension) {
                if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))) {
                    alert('只支持jpg、png、gif格式的文件！');
                    return false;
                }
            },
            onComplete: function (file, r) {
                if (r != null && r.code == 200) {
                    $("#articleCoverImg").attr("src", r.data);
                    // window.console.log(r.data);
                    // window.console.log($("#articleCoverImg").attr("src"));
                    src=r.data;
                    $("#articleCoverImg").attr("style", "width: 128px;height: 128px;display:block;");
                    return false;
                } else {
                    alert("error");
                }
            }
        });

    });
    $('#publishArticle').click(function () {
        var title = $('#title').val();
        // var goodsCategoryId = $('#levelThree option:selected').val();
        var introduce = $('#introduce').val().trim();
        var content = $('#content').val().trim();
        var kindId=$('#kindId').val();
        var tags=$('#tags').val();

        console.log(introduce);
        console.log(tags);
        console.log(src);
        // console.log($('#articleCoverImg')[0].src);
        // console.log($('#articleCoverImg')[0]);
        // console.log(document.getElementById("articleCoverImg").src);



        // var articleCoverImg = $('#articleCoverImg')[0].src;这里不知道为啥从DOM对象里取出来的src自动加了http://localhost:9000/前缀，打印
        //dom对象src正常，网页代码里面也正常，不知道怎么解决；这里暂时先用全局变量src
        var articleCoverImg=src;
        var articleId=Id;

        if (isNull(title)) {
            swal("请输入文章名称", {
                icon: "error",
            });
            return;
        }
        if (!validLength(title, 100)) {
            swal("名称过长", {
                icon: "error",
            });
            return;
        }

        if (isNull(introduce)) {
            swal("请输入简介", {
                icon: "error",
            });
            return;
        }
        if (!validLength(introduce, 200)) {
            swal("简介过长", {
                icon: "error",
            });
            return;
        }

        if (isNull(content)) {
            swal("请输入文章内容", {
                icon: "error",
            });
            return;
        }

        if (isNull(articleCoverImg) || articleCoverImg.indexOf('img-upload') != -1) {
            swal("封面图片不能为空", {
                icon: "error",
            });
            return;
        }
        if(isNull(kindId)){
            swal("请选择分类",{
                icon:"error",
            });
            return ;
        }
        if(tags.length==0){
            swal("请选择标签",{
                icon:"error",
            });
            return ;
        }
        var url = '/doEditArticle';
        var swlMessage = '保存成功';
        var data = {
            "title": title,
            "content": content,
            "introduce": introduce,
            "img": articleCoverImg,
            "kindId":kindId,
            "tags":tags,
            "id":articleId
        };

        console.log(data);
        console.log(JSON.stringify(data));
        $.ajax({
            type: 'POST',//方法类型
            url: url,
            contentType: 'application/json',
            data: JSON.stringify(data),
            //data:{title:title,content:content,introduce:introduce,articleCoverImg:articleCoverImg},//这个应该不是json格式,所以不能指定contentType: 'application/json'
            dataType: "json",
            success: function (result) {
                //if (result.code == 200)
                if (result.code==200) {
                    console.log(result.code);
                    console.log(result.data);
                    swal({
                        title: swlMessage,
                        type: 'success',
                        showCancelButton: false,
                        confirmButtonColor: '#1baeae',
                        confirmButtonText: '返回',
                        confirmButtonClass: 'btn btn-success',
                        buttonsStyling: false
                    }).then(function () {
                        window.location.href = "/publishedArticleManage";
                    })
                } else {
                    swal(result.message, {
                        icon: "error",
                    });
                }
                ;
            },
            error: function () {
                swal("操作失败", {
                    icon: "error",
                });
            }
        });
    });
</script>
<script src="common/tagsinput/jquery.color.plus-names.min.js"></script>
<script src="common/tagsinput/jquery-tagsinput.min.js" defer></script>
<script src="common/js/article.js"></script>
<script src="common/js/sweetalert.min.js"></script>
<script src="common/js/common.js"></script>

<script src="common/js/public.js"></script>
<script src="background/ajaxupload/ajaxupload.js"></script>
<script>
    $(document).ready(function () {
        $('[data-role="tags-input"]').tagsInput();
        // $('.dropdown-toggle').addEventListener('o')
    });


</script>
</body>
</html>